package com.smartao.core.orm.hibernate;

import org.hibernate.cfg.ImprovedNamingStrategy;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.internal.util.StringHelper;

/**
 * Hibernate命名策略,驼峰命名法,表名和列名均转化为大写字母
 * @author Ricky
 *
 */
public class SmartaoNamingStrategy extends ImprovedNamingStrategy {

	private static final long serialVersionUID = -1656372704946142264L;

	public static final NamingStrategy INSTANCE = new SmartaoNamingStrategy();
	
	@Override
	public String classToTableName(String className) {
		return addUnderscores( StringHelper.unqualify(className) );
	}
	/**
	 * Return the full property path with underscore seperators, mixed
	 * case converted to underscores
	 */
	@Override
	public String propertyToColumnName(String propertyName) {
		return addUnderscores( StringHelper.unqualify(propertyName) );
	}
	/**
	 * Convert mixed case to underscores
	 */
	@Override
	public String tableName(String tableName) {
		return addUnderscores(tableName);
	}
	/**
	 * Convert mixed case to underscores
	 */
	@Override
	public String columnName(String columnName) {
		return addUnderscores(columnName);
	}

	/**
	 * 表名和列名均转化为大写字母
	 * @param name
	 * @return
	 */
	protected static String addUnderscores(String name) {
		StringBuffer buf = new StringBuffer( name.replace('.', '_') );
		for (int i=1; i<buf.length()-1; i++) {
			if (
				Character.isLowerCase( buf.charAt(i-1) ) &&
				Character.isUpperCase( buf.charAt(i) ) &&
				Character.isLowerCase( buf.charAt(i+1) )
			) {
				buf.insert(i++, '_');
			}
		}
		return buf.toString().toUpperCase();
	}
}
